<template>
	<view class="big_box">
		<u-navbar :title="tabTitle" @rightClick="rightClick" :autoBack="true">
		</u-navbar>
		<view class="list">
			<view class="list_item" v-for="item in qunData.list" :key="item.id">
				<view class="left" @click="showClick(item)">
					<image :src="item.image" mode=""></image>
					<view class="sub_text">
						<view class="title">
							{{item.name}}
							<!-- <span v-if="item.status==1">(已满)</span>
							<span v-else>(可加)</span> -->
						</view>
						<view class="desc">
							{{item.nums}}
						</view>
					</view>
				</view>
				<!-- <u-button type="primary" class="custom-style" shape="circle" :plain="true"
					@click="go_add(item.id)">入群</u-button> -->
			</view>
		</view>
		<view class="red">
			<view class="text">
				{{ qunData.title }}
			</view>
			<image src="/static/index_image/finger.png" mode=""></image>
		</view>
		<view class="qrcode">
			<view class="code" v-if="!is_buy" :style="{backgroundImage: `url(${selectedImage})`}">
				<view class="title_box">
					<image :src="qunData.info.image" mode=""></image>
					<view class="title">
						{{qunData.info.name}}
					</view>
				</view>
				<view class="paytext">
					<view class="price">
						支付<span>{{price}}</span> 元后可进群
					</view>
					<view class="btn" @click="tobuy()">
						点击支付>
					</view>
				</view>
			</view>
			<view class="togo" v-else>
				<image :src="qunData.info.qun_image" style="width: 100%;" mode="widthFix"></image>
			</view>
		</view>
		<!-- <view class="vip">
			<view class="vip_line"></view>
			<view class="vip_circle"></view>
			<span>VIP会员3大特权</span>
			<view class="vip_circle vip_circle2"></view>
			<view class="vip_line vip_line2"></view>
		</view> -->
		<view class="banner_image">
			<image :src="qunData.quanyi_image" style="width: 100%;" mode="widthFix"></image>
		</view>
		<view class="footer">
			<view class="order" @click="go_order()">
				<u-icon name="file-text" size="20" color="#e02e24"></u-icon>
				<view class="name">
					订单
				</view>
			</view>
			<view class="right_btn" v-if="!is_buy">
				<view class="text">
					支付{{price}}元进入本群
				</view>
				<view class="btn" @click="tobuy()">
					支付
				</view>
			</view>
			<view class="right_btn" v-if="is_buy">
				<view class="text">
					已经支付
				</view>
			</view>

		</view>
		<!-- 加群弹窗 -->
		<u-modal :show="show" :title="tabTitle" @confirm="confirm" confirmColor='#7dc5eb'
			:content="content+qunData.info.name"></u-modal>
		<!-- 没有购买权限 -->
		<u-popup :show="is_show" mode="center" :round="10">
			<view class="pop_box">
				<image src="/static/index_image/msg-error.png" mode=""></image>
				<text>暂无购买本群的权限</text>
				<u-button class="custom-style" type="primary" text="确定" @click="close"></u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		mapGetters
	} from "vuex";
	import api from '@/api/index.js'
	export default {
		data() {
			return {
				tabTitle: '',
				show: false,
				content: '本群人数已达到上线，请进',
				selectedImage: '/static/index_image/qrcode.jpg',
				price: '',
				num: '4',
				is_show: false,
				pay_show: true,
				listData: [],
				qun_id: '',
				qunData: {

				},
				order_id: '',
				jssdkData: {},
				isWechat: '',
				is_buy:'',
			}
		},
		computed: mapGetters(['isLogin', 'uid', 'userInfo']),
		onLoad(option) {
			console.log(JSON.parse(option.data), 'option');
			let value = JSON.parse(option.data)
			this.tabTitle = value.name
			this.qun_id = value.id
			this.price = value.price
			this.getProvinceList()
			// // 检测是否微信环境
			// this.isWechat = /MicroMessenger/i.test(navigator.userAgent);
			// // 如果是微信环境，预加载JS-SDK
			// if (this.isWechat) {
			// 	this.getjssdk();
			// }

		},
		methods: {
			rightClick() {
				console.log('rightClick');
			},
			//获取数据
			getProvinceList() {
				api.getaddqunList({
					qun_id: this.qun_id
				}).then(res => {
					if (res.response.statusCode == 200) {
						this.qunData = res.data.data
						// is_buy:0//未购买,1已购买
						console.log(this.qunData, 'this.qunData');
						this.is_buy=this.qunData.is_buy
					}
				}).catch(err => {
					console.error(err)
				})
			},
			//加群
			showClick(item) {
				if (item.nums) {
					this.show = true
				}
			},
			//确认
			confirm() {
				this.show = false;
			},
			// 购买/支付方法
			async tobuy() {
				if (!uni.getStorageSync('token')) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}

				try {
					uni.showLoading({
						title: '创建订单中...'
					});

					// 1. 创建订单
					const orderRes = await api.createOrder({
						qun_id: this.qun_id || 1
					});

					if (orderRes.response.statusCode !== 200) {
						throw new Error('创建订单失败');
					}

					this.order_id = orderRes.data.data.order_id;
					// 2. 获取支付参数 + JSSDK配置
					const [payParamsRes, jssdkRes] = await Promise.all([
						api.orderPay({
							order_id: this.order_id
						}),
						api.getjssdk({
							url: window.location.href.split('#')[0],
							platform: 'wechat'
						})
					]);

					if (payParamsRes.response.statusCode !== 200 || jssdkRes.response.statusCode !== 200) {
						throw new Error('获取支付参数失败');
					}

					// 3. 初始化微信JS-SDK
					await this.initWechatJSSDK(jssdkRes.data.data);

					// 4. 调用支付
					await this.wechatH5Pay(payParamsRes.data.data);

				} catch (error) {
					console.error('支付失败:', error);
					uni.showToast({
						title: error.message || '支付失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 初始化微信JS-SDK
			initWechatJSSDK(jssdkConfig) {
				return new Promise((resolve, reject) => {
					if (typeof window.WeixinJSBridge !== 'undefined') {
						resolve();
						return;
					}

					const script = document.createElement('script');
					script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
					script.onload = () => {
						wx.config({
							debug: false, // 生产环境设为false
							appId: jssdkConfig.appId,
							timestamp: jssdkConfig.timestamp,
							nonceStr: jssdkConfig.nonceStr,
							signature: jssdkConfig.signature,
							jsApiList: ['chooseWXPay'] // 需要使用的JS接口列表
						});

						wx.ready(() => {
							resolve();
						});

						wx.error((err) => {
							reject(new Error('微信JSSDK初始化失败'));
						});
					};
					script.onerror = () => {
						reject(new Error('加载微信JS-SDK失败'));
					};
					document.body.appendChild(script);
				});
			},

			// 微信H5支付
			wechatH5Pay(paymentParams) {
				return new Promise((resolve, reject) => {
					// 检查是否在微信环境
					if (typeof window.WeixinJSBridge === 'undefined') {
						// 如果不在微信环境，引导用户到外部浏览器支付
						window.location.href = paymentParams.mweb_url + '&redirect_url=' + encodeURIComponent(
							window.location.href);
						return;
					}

					// 微信内支付
					window.WeixinJSBridge.invoke(
						'getBrandWCPayRequest', {
							appId: paymentParams.appId,
							timeStamp: paymentParams.timeStamp.toString(),
							nonceStr: paymentParams.nonceStr,
							package: paymentParams.package,
							signType: paymentParams.signType,
							paySign: paymentParams.paySign
						},
						(res) => {
							if (res.err_msg === 'get_brand_wcpay_request:ok') {
								resolve();
								this.handlePaySuccess();
							} else {
								reject(new Error('支付失败: ' + res.err_msg));
							}
						}
					);
				});
			},



			handlePaySuccess() {

				uni.navigateTo({
					url: '/pages/mine/order_list'
				})
			},
			//关闭
			close() {
				this.is_show = false
			},
			//订单
			go_order() {
				uni.navigateTo({
					url: '/pages/mine/order_list'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	@mixin flex-center-between {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	@mixin flex-center-column {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.big_box {

		.list {
			display: flex;
			flex-wrap: wrap;
			border-top: 1px solid #f1f1f1;
			margin-top: 2rem;
			background-color: #fff;
			padding: 1rem;

			.list_item {
				width: 50%;
				@include flex-center-between;
				margin: .5rem 0;

				.left {
					display: flex;
					align-items: center;

					image {
						width: 3rem;
						height: 3rem;
						border-radius: .8rem;
					}

					.title {
						font-size: .8rem;
						font-weight: 600;
						color: #191919;

						span {
							font-size: .8rem;
							color: #7e7e7e;
						}
					}

					.desc {
						font-size: .8rem;
						color: #7e7e7e;
					}
				}

				.custom-style {
					width: 4rem;
					height: 1.5rem;
					line-height: 1.5rem;
					font-size: .8rem;
					margin: 0;
				}
			}
		}

		.red {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 1rem;

			.text {
				font-size: 1rem;
				color: #f47474;
			}

			image {
				width: 2.6rem;
				height: 0.92rem;
				margin-left: 0.6rem;
			}
		}

		.qrcode {
			margin: 1rem 0;
			background-color: #ededed;
			padding: .8rem 1rem;

			.code {
				width: 100%;
				border-radius: .5rem;
				@include flex-center-column;
				background-repeat: no-repeat;
				background-size: cover;
				height: 420px;
				position: relative;

				.title_box {
					display: flex;
					align-items: center;
					margin-top: 2rem;

					image {
						width: 4rem;
						height: 4rem;
					}

					.title {
						font-size: 1.25rem;
					}
				}

				.paytext {
					position: absolute;
					top: 14rem;
					margin: auto;
					@include flex-center-column;

					.price {
						font-size: 1.25rem;
						color: #fff;

						span {
							color: #7dc5eb;
						}
					}

					.btn {
						font-size: 1rem;
						color: #34b449;
					}
				}
			}
		}

		.vip {
			width: 90%;
			margin: 0 auto;
			text-align: center;
			display: flex;
			align-items: center;
			justify-content: center;
			padding-top: 3rem;

			.vip_line {
				width: 2rem;
				height: 0.1rem;
				background: linear-gradient(to right, #fbf4eb, #65a0bd);
			}

			.vip_circle {
				width: 0.2rem;
				height: 0.2rem;
				border-radius: 50%;
				border: solid 0.1rem #65a0bd;
				margin-left: 0.4rem;
			}

			span {
				font-size: 1.39rem;
				background: linear-gradient(to bottom, #7dc5eb, #65a0bd);
				-webkit-background-clip: text;
				color: transparent;
				font-family: arial;
				font-weight: bold;
				padding: 0 0.92rem;
			}

			.vip_line2 {
				margin-left: 0.4rem;
				background: linear-gradient(to right, #65a0bd, #fbf4eb);
			}

			.vip_circle2 {
				margin-left: -0.4rem;
			}
		}

		.footer {
			width: 100%;
			margin: 0 auto;
			position: fixed;
			bottom: 1rem;
			@include flex-center-between;

			.order {
				width: 3rem;
				height: 3rem;
				background-color: #fff;
				border-radius: 50%;
				box-shadow: 3px 5px 25px #c2c2c2;
				@include flex-center-column;
				color: #e02e24;
				justify-content: center;
				margin-left: .5rem;

				.name {
					font-size: .8rem;
				}
			}

			.right_btn {
				height: 3rem;
				width: 80%;
				background-color: #e02e24;
				border-radius: 5rem;
				box-shadow: 3px 5px 25px #c2c2c2;
				text-align: center;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #fff;
				margin-right: .5rem;

				.text {
					font-size: 1rem;
					width: 70%;
				}

				.btn {
					width: 20%;
					color: #e02e24;
					background-color: #fff;
					font-size: 1rem;
					padding: 0.4rem 0.2rem;
					border-radius: 5rem;
					font-weight: bold;
				}
			}
		}

		.pop_box {
			@include flex-center-column;
			padding: 1rem;

			image {
				width: 4rem;
				height: 4rem;
			}

			text {
				font-size: 1rem;
				margin: 1rem 0;
			}

			.custom-style {
				width: 20rem;
				height: 2rem;
				line-height: 1.5rem;
				font-size: .8rem;
				margin: 0;
				background-color: #7dc5eb;
				border-color: #7dc5eb;
			}
		}
	}
</style>